/* 内部API（自家服务器接口） */

import axios from "axios";
import { alertError } from "@/util/alert";
import { watch } from "vue";

export const api = axios.create({
	baseURL: 'http://localhost:8080', // 系统专用服务器API基地址
	timeout: 10000
})

api.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`
watch (() => localStorage.getItem('token'), (token) => {
	console.log(token)
	api.defaults.headers.common['Authorization'] = `Bearer ${token}`
})

const axiosErrorMessages = {
  "Network Error": "网络异常，服务器连接失败",
  "ECONNREFUSED": "连接被拒绝",
  "ETIMEDOUT": "连接超时",
  "CORS Error": "跨域错误",
  "Request aborted": "请求被取消",
  "Invalid URL": "无效的URL",
  "Response Error": "响应错误",
  "JSON Parse Error": "JSON解析错误",
  "Axios Cancel Error": "Axios取消错误",
  "No Internet Connection": "无网络连接"
};

api.interceptors.response.use(
	response => response,
	error => {
		const message = error.response?.data?.message
		if (message) {
			alertError(message)
			console.error(message)
		} else {
			alertError(axiosErrorMessages[error.message] || error.message)
			console.error(error)
		}
		return Promise.reject(error);
	}
)